package com.shuorikeji.huohuo.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bytedance.sdk.djx.DJXSdk;
import com.bytedance.sdk.djx.IDJXService;
import com.bytedance.sdk.djx.model.DJXDrama;
import com.bytedance.sdk.djx.model.DJXError;
import com.bytedance.sdk.djx.model.DJXOthers;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.material.imageview.ShapeableImageView;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.MhSearAdapter;
import com.shuorikeji.huohuo.adapter.SearchHisHotAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.AllBookMainBean;
import com.shuorikeji.huohuo.bean.BookDetailInfoTempBean;
import com.shuorikeji.huohuo.bean.HotSearchMainBean;
import com.shuorikeji.huohuo.bean.MhInfoBean;
import com.shuorikeji.huohuo.bean.MhInfoMainBean;
import com.shuorikeji.huohuo.bean.SearchHistoryInfoBean;
import com.shuorikeji.huohuo.bean.SearchHistoryMainBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.ui.dj.DjXqActivity;
import com.shuorikeji.huohuo.ui.home.BookInfoActivity;
import com.shuorikeji.huohuo.ui.home.MoreBdActivity;
import com.shuorikeji.huohuo.ui.mh.MhDetailActivity;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.JsonUtil;
import com.shuorikeji.huohuo.utils.SpacesItemDecoration;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

public class SearchActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_delete_s_ls)
    ImageView ivDeleteSLs;//删除搜索历史
    @BindView(R.id.rv_search_history)
    RecyclerView rvSsLs;//搜索历史
    @BindView(R.id.tv_mh_tag)
    TextView tvMhTag;
    @BindView(R.id.tv_book_tag)
    TextView tvBookTag;
    @BindView(R.id.tv_dj_tag)
    TextView tvDjTag;
    @BindView(R.id.rv_hot_search_mh)
    RecyclerView rvHotSearchMh;
    @BindView(R.id.rv_hot_search_book)
    RecyclerView rvHotSearchBook;
    @BindView(R.id.rv_hot_search_dj)
    RecyclerView rvHotSearchDj;
    @BindView(R.id.ll_all)
    LinearLayout llAllTab;
    @BindView(R.id.tv_all)
    TextView tvAllTab;
    @BindView(R.id.iv_all)
    ImageView ivAllTab;
    @BindView(R.id.ll_mh_tab)
    LinearLayout llMhTab;
    @BindView(R.id.tv_mh_tab)
    TextView tvMhTab;
    @BindView(R.id.iv_mh_tab)
    ImageView ivMhTab;
    @BindView(R.id.ll_book_tab)
    LinearLayout llBookTab;
    @BindView(R.id.tv_book_tab)
    TextView tvBookTab;
    @BindView(R.id.iv_book_tab)
    ImageView ivBookTab;
    @BindView(R.id.ll_dj_tab)
    LinearLayout llDjTab;
    @BindView(R.id.tv_dj_tab)
    TextView tvDjTab;
    @BindView(R.id.iv_dj_tab)
    ImageView ivDjTab;
    @BindView(R.id.rv_mh)
    RecyclerView rvMh;//搜索出的漫画数据
    @BindView(R.id.ll_dj_sear_content_ui)
    LinearLayout llDjSearUi;//短剧搜索的UI
    @BindView(R.id.tv_more_dj_data)
    TextView tvMoreDj;//更多短剧
    @BindView(R.id.iv_more_dj_data)
    ImageView ivMoreDj;//更多短剧
    @BindView(R.id.ll_dj_sear_data)
    LinearLayout llDjSearData;//短剧搜索出的数据
    @BindView(R.id.ll_book_sear_content_ui)
    LinearLayout llBookSearUi;//小说搜索的UI
    @BindView(R.id.tv_more_book_data)
    TextView tvMoreBook;//更多小说
    @BindView(R.id.iv_more_book_data)
    ImageView ivMoreBook;//更多小说
    @BindView(R.id.ll_book_sear_data)
    LinearLayout llBookSearData;//小说搜索出的数据

    private List<MhInfoBean> mhList = new ArrayList<>();
    private List<BookDetailInfoTempBean> bookList = new ArrayList<>();
    private List<SearchHistoryInfoBean> searHisList = new ArrayList<>();
    private SearchHisHotAdapter searchHisHotAdapter;
    private MhSearAdapter mhSearAdapter;
    private int searchTag;
    private SearchHisHotAdapter hotSearchAdapter;
    private List<SearchHistoryInfoBean> hotSearList = new ArrayList<>();
    private SearchHisHotAdapter bookHotSearchAdapter;
    private List<SearchHistoryInfoBean> bookHotSearList = new ArrayList<>();
    private List<DJXDrama> djList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_search);
    }

    @Override
    protected void initData() {
        ivClear.setVisibility(View.GONE);
        initAdapter();
        setHotSearTagView(1);
        getMhHotSear();
        setSearContentTabView(1);
        getSearchHistory();
        initClick();
    }

    private void initAdapter() {
        FlexboxLayoutManager manager = new FlexboxLayoutManager(this);
        manager.setFlexDirection(FlexDirection.ROW);
        manager.setFlexWrap(FlexWrap.WRAP);
        rvSsLs.addItemDecoration(new GridDividerItemDecoration(20));
        rvSsLs.setLayoutManager(manager);
        searchHisHotAdapter = new SearchHisHotAdapter(SearchActivity.this, 1, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        String content = (String) object;
                        etSearch.setText(content);
                        getSearContent();
                        break;
                    case 2:
                        SearchHistoryInfoBean data = (SearchHistoryInfoBean) object;
                        deleteMhSearchHis(data.getId());
                        deleteBookSearchHis(data.getId());
                        break;
                }
            }
        });
        rvSsLs.setAdapter(searchHisHotAdapter);

        FlexboxLayoutManager manager1 = new FlexboxLayoutManager(this);
        manager1.setFlexDirection(FlexDirection.ROW);
        manager1.setFlexWrap(FlexWrap.WRAP);
        rvHotSearchMh.addItemDecoration(new GridDividerItemDecoration(20));
        rvHotSearchMh.setLayoutManager(manager1);
        hotSearchAdapter = new SearchHisHotAdapter(SearchActivity.this, 1, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        String content = (String) object;
                        etSearch.setText(content);
                        getSearContent();
                        break;
                }
            }
        });
        rvHotSearchMh.setAdapter(hotSearchAdapter);

        FlexboxLayoutManager manager2 = new FlexboxLayoutManager(this);
        manager2.setFlexDirection(FlexDirection.ROW);
        manager2.setFlexWrap(FlexWrap.WRAP);
        rvHotSearchBook.addItemDecoration(new GridDividerItemDecoration(20));
        rvHotSearchBook.setLayoutManager(manager2);
        bookHotSearchAdapter = new SearchHisHotAdapter(SearchActivity.this, 1, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        String content = (String) object;
                        etSearch.setText(content);
                        getSearContent();
                        break;
                }
            }
        });
        rvHotSearchBook.setAdapter(bookHotSearchAdapter);

        rvMh.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rvMh.addItemDecoration(new SpacesItemDecoration(0, 0, 10, 0));
        mhSearAdapter = new MhSearAdapter(mContext, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        MhInfoBean data = (MhInfoBean) object;
                        Intent intent = new Intent(SearchActivity.this, MhDetailActivity.class);
                        intent.putExtra("MH_ID", data.getId());
                        startActivity(intent);
                        break;
                }
            }
        });
        rvMh.setAdapter(mhSearAdapter);
    }

    /**
     * 热门搜索标签
     *
     * @param flag 1漫画
     *             2小说
     *             3短剧
     */
    private void setHotSearTagView(int flag) {
        searchTag = flag;
        tvMhTag.setBackground((flag == 1) ? getResources().getDrawable(R.drawable.shape_8_f9e141) : getResources().getDrawable(R.drawable.shape_8_f5f5f5));
        tvMhTag.setTextColor((flag == 1) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_666666));
        rvHotSearchMh.setVisibility((flag == 1) ? View.VISIBLE : View.GONE);

        tvBookTag.setBackground((flag == 2) ? getResources().getDrawable(R.drawable.shape_8_f9e141) : getResources().getDrawable(R.drawable.shape_8_f5f5f5));
        tvBookTag.setTextColor((flag == 2) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_666666));
        rvHotSearchBook.setVisibility((flag == 2) ? View.VISIBLE : View.GONE);

        tvDjTag.setBackground((flag == 3) ? getResources().getDrawable(R.drawable.shape_8_f9e141) : getResources().getDrawable(R.drawable.shape_8_f5f5f5));
        tvDjTag.setTextColor((flag == 3) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_666666));
        rvHotSearchDj.setVisibility((flag == 3) ? View.VISIBLE : View.GONE);
    }

    /**
     * 搜索返回的内容标签
     *
     * @param flag 1综合
     *             2漫画
     *             3小说
     *             4短剧
     */
    private void setSearContentTabView(int flag) {
        tvAllTab.setTextColor((flag == 1) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvAllTab, ((flag == 1) ? true : false));
        ivAllTab.setVisibility((flag == 1) ? View.VISIBLE : View.INVISIBLE);

        tvMhTab.setTextColor((flag == 2) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvMhTab, ((flag == 2) ? true : false));
        ivMhTab.setVisibility((flag == 2) ? View.VISIBLE : View.INVISIBLE);

        tvBookTab.setTextColor((flag == 3) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvBookTab, ((flag == 3) ? true : false));
        ivBookTab.setVisibility((flag == 3) ? View.VISIBLE : View.INVISIBLE);

        tvDjTab.setTextColor((flag == 4) ? getResources().getColor(R.color.color_333333) : getResources().getColor(R.color.color_999999));
        BusinessUtils.setTxtFold(tvDjTab, ((flag == 4) ? true : false));
        ivDjTab.setVisibility((flag == 4) ? View.VISIBLE : View.INVISIBLE);
        if (flag == 1) {
            rvMh.setVisibility(View.VISIBLE);
            llBookSearUi.setVisibility(View.VISIBLE);
            llDjSearUi.setVisibility(View.VISIBLE);
        } else if (flag == 2) {
            rvMh.setVisibility(View.VISIBLE);
            llBookSearUi.setVisibility(View.GONE);
            llDjSearUi.setVisibility(View.GONE);
        } else if (flag == 3) {
            rvMh.setVisibility(View.GONE);
            llBookSearUi.setVisibility(View.VISIBLE);
            llDjSearUi.setVisibility(View.GONE);
        } else if (flag == 4) {
            rvMh.setVisibility(View.GONE);
            llBookSearUi.setVisibility(View.GONE);
            llDjSearUi.setVisibility(View.VISIBLE);
        }
    }

    private void getSearchHistory() {
        switch (searchTag) {
            case 1:
                getMhSearchHistory();
                break;
            case 2:
                getBookSearchHistory();
                break;
        }
    }

    /**
     * 漫画热门搜索
     */
    private void getMhHotSear() {
        mPresenter.mhHotSearch(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        HotSearchMainBean data = (HotSearchMainBean) object;
                        hotSearList.clear();
                        hotSearList.addAll(data.getData().getData());
                        hotSearchAdapter.setData(hotSearList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 小说热门搜索
     */
    private void getBookHotSear() {
        mPresenter.bookHotSearch(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        HotSearchMainBean data = (HotSearchMainBean) object;
                        bookHotSearList.clear();
                        bookHotSearList.addAll(data.getData().getData());
                        bookHotSearchAdapter.setData(bookHotSearList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getMhSearchHistory() {
        mPresenter.mhSearchHistory(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        SearchHistoryMainBean data = (SearchHistoryMainBean) object;
                        searHisList.clear();
                        searHisList.addAll(data.getData());
                        searchHisHotAdapter.setData(searHisList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getBookSearchHistory() {
        mPresenter.bookSearchHistory(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        SearchHistoryMainBean data = (SearchHistoryMainBean) object;
                        searHisList.clear();
                        searHisList.addAll(data.getData());
                        searchHisHotAdapter.setData(searHisList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getSearContent() {
        getAllMh(etSearch.getText().toString());
        getAllBook(etSearch.getText().toString());
        getDjList(etSearch.getText().toString());
    }

    /**
     * 获取所有漫画
     */
    private void getAllMh(String content) {
        mPresenter.getAllMh(2, -1, 100, 1, content, "", -1, -1, -1, -1,
                -1, -1, -1, -1, -1, -1, true, new ClickCallBack() {
                    @Override
                    public void onClick(int flag, Object object) {
                        switch (flag) {
                            case 1:
                                MhInfoMainBean data = (MhInfoMainBean) object;
                                mhList.clear();
                                mhList.addAll(data.getData().getData());
                                mhSearAdapter.setData(mhList);
                                break;
                            case 2:
                                String msg = (String) object;
                                ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                                break;
                        }
                    }
                });
    }

    private void getAllBook(String content) {
        mPresenter.getAllBook(SearchActivity.this, 10, -1, 100, 1, content, -1,
                -1, -1, -1, -1, -1, -1, -1,
                -1, -1, "", -1, true, new ClickCallBack() {
                    @Override
                    public void onClick(int flag, Object object) {
                        switch (flag) {
                            case 1:
                                AllBookMainBean data = (AllBookMainBean) object;
                                bookList.clear();
                                bookList.addAll(data.getData().getData());
                                showBookView();
                                break;
                            case 2:
                                String msg = (String) object;
                                ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        }
                    }
                });
    }

    private void getDjList(String content) {
        DJXSdk.service().searchDrama(content, true, 1, 20, new IDJXService.IDJXCallback<List<? extends DJXDrama>>() {
            @Override
            public void onSuccess(List<? extends DJXDrama> djxDramas, @Nullable DJXOthers djxOthers) {
                djList.clear();
                djList.addAll(djxDramas);
                showDjView();
            }

            @Override
            public void onError(@NonNull DJXError djxError) {

            }
        });
    }

    private void showDjView() {
        llDjSearData.removeAllViews();
        for (int i = 0; i < djList.size(); i++) {
            View subView = View.inflate(SearchActivity.this, R.layout.dj_search_item_layout, null);
            subView.setPadding(0, 0, 40, 0);
            LinearLayout llMain = subView.findViewById(R.id.ll_main);
            TextView tvName = subView.findViewById(R.id.tv_title);
            TextView tvTag = subView.findViewById(R.id.tv_tag);
            ShapeableImageView sivFm = subView.findViewById(R.id.siv_fm);
            BusinessUtils.setLoadImg(SearchActivity.this, djList.get(i).coverImage, sivFm);
            tvName.setText(djList.get(i).title);
            tvTag.setText(djList.get(i).type);
            llMain.setId(i);
            llDjSearData.addView(subView);
            llMain.setOnClickListener(view -> {
                Intent intent = new Intent(SearchActivity.this, DjXqActivity.class);
                intent.putExtra("dramaId", djList.get(llMain.getId()).id);
                intent.putExtra("dramaBean", JsonUtil.toJson(djList.get(llMain.getId())));
                startActivity(intent);
            });
        }
    }

    /**
     * 显示搜索出的小说
     */
    private void showBookView() {
        llBookSearData.removeAllViews();
        for (int i = 0; i < bookList.size(); i++) {
            View subView = View.inflate(SearchActivity.this, R.layout.sear_book_item_layout, null);
            subView.setPadding(0, 0, 40, 0);
            LinearLayout llMain = subView.findViewById(R.id.ll_main);
            TextView tvName = subView.findViewById(R.id.tv_mh_name);
            TextView tvTag = subView.findViewById(R.id.tv_mh_tag);
            ShapeableImageView sivFm = subView.findViewById(R.id.siv_fm);
            BusinessUtils.setLoadImg(SearchActivity.this, Constant.IMG_OSS_BASE_URL + bookList.get(i).getCover_image(), sivFm);
            tvName.setText(bookList.get(i).getName());
            tvTag.setText(BusinessUtils.getMhTag(bookList.get(i).getTag_id()));
            llMain.setId(i);
            llBookSearData.addView(subView);
            llMain.setOnClickListener(view -> {
                Intent intent = new Intent(SearchActivity.this, BookInfoActivity.class);
                intent.putExtra("BOOK_ID", bookList.get(llMain.getId()).getId());
                startActivity(intent);
            });
        }
    }

    /**
     * 删除小说搜索历史
     *
     * @param id id
     */
    private void deleteBookSearchHis(int id) {
        mPresenter.deleteBookSearHis(id, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        getSearchHistory();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 删除漫画搜索历史
     *
     * @param id id
     */
    private void deleteMhSearchHis(int id) {
        mPresenter.deleteMhSearHis(id, true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        getSearchHistory();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SearchActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void initClick() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (BusinessUtils.isEmpty(charSequence.toString())) {
                    ivClear.setVisibility(View.GONE);
                } else {
                    ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        ivBack.setOnClickListener(view -> {
            finish();
        });
        ivClear.setOnClickListener(view -> {
            etSearch.setText("");
        });
        tvSearch.setOnClickListener(view -> {
            //开始搜索
            if (BusinessUtils.isEmpty(etSearch.getText().toString())) {
                ToastShowUtil.showToastCenter(SearchActivity.this, "请输入搜索内容");
            } else {
                getSearContent();
            }
        });
        ivDeleteSLs.setOnClickListener(view -> {
            //删除搜索历史
            if (searHisList != null && searHisList.size() > 0) {
                if (searHisList != null && searHisList.size() > 0) {
                    for (int i = 0; i < searHisList.size(); i++) {
                        if (searHisList.get(i).isDelete()) {
                            searHisList.get(i).setDelete(false);
                        } else {
                            searHisList.get(i).setDelete(true);
                        }
                    }
                    searchHisHotAdapter.setData(searHisList);
                } else {
                    ToastShowUtil.showToastCenter(SearchActivity.this, "暂无搜索历史");
                }
            }
        });
        tvMhTag.setOnClickListener(view -> {
            setHotSearTagView(1);
            getMhHotSear();
        });
        tvBookTag.setOnClickListener(view -> {
            setHotSearTagView(2);
            getBookHotSear();
        });
        tvDjTag.setOnClickListener(view -> {
            setHotSearTagView(3);
        });
        llAllTab.setOnClickListener(view -> {
            setSearContentTabView(1);
        });
        llMhTab.setOnClickListener(view -> {
            setSearContentTabView(2);
        });
        llBookTab.setOnClickListener(view -> {
            setSearContentTabView(3);
        });
        llDjTab.setOnClickListener(view -> {
            setSearContentTabView(4);
        });
        tvMoreDj.setOnClickListener(view -> {
            ToastShowUtil.showToastCenter(SearchActivity.this, "更多短剧");
        });
        ivMoreDj.setOnClickListener(view -> {
            ToastShowUtil.showToastCenter(SearchActivity.this, "更多短剧");
        });
        tvMoreBook.setOnClickListener(view -> {
            Intent intent = new Intent(SearchActivity.this, MoreBdActivity.class);
            startActivity(intent);
        });
        ivMoreBook.setOnClickListener(view -> {
            Intent intent = new Intent(SearchActivity.this, MoreBdActivity.class);
            startActivity(intent);
        });
    }
}